package com.arvato.common.ftp;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
  
/** 
 * 
 * @author: smallking
 * 
 * @Descibe:用来操作ftp的综合类 ftp正常一步步看代码就ok了。但是有一个坑就是ftp的主动模式和被动模式。
 * 
 * @Date: 2018年5月15日  下午4:58:44
 */
public class FtpUtil implements AutoCloseable {

    private FTPClient ftpClient;

    private  Logger logger = LoggerFactory.getLogger(FtpUtil.class);

    public FtpUtil(String serverIP, int port, String userName, String password) throws IOException {
        ftpClient = new FTPClient();
        ftpClient.connect(serverIP, port);
        ftpClient.setControlEncoding("UTF-8");//设置编码
        ftpClient.login(userName, password);
        ftpClient.setBufferSize(1024);//设置上传缓存大小
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);//设置文件类型
    }

    /**
     * 下载ftp文件到本地
     *
     * @param remoteFileName 远程文件名称
     * @param localFile      本地文件[包含路径]
     * @return true/false
     * @throws IOException 异常
     */
    public boolean downloadFile(String remoteFileName, String localFile) throws IOException {
        boolean isSucc;
        File outFileName = new File(localFile);
        if (ftpClient == null)
            throw new IOException("ftp server not login");
        try (OutputStream outputStream = new FileOutputStream(outFileName)) {
            isSucc = ftpClient.retrieveFile(remoteFileName, outputStream);
        }
        return isSucc;
    }

    /**
     * 浏览器预览图片
     * @param remoteFileName 远程文件名称
     * @param outputStream      本地文件[包含路径]
     * @return true/false
     * @throws IOException 异常
     */
    public boolean downloadFile(String remoteFileName, OutputStream outputStream) throws IOException {
        boolean isSucc;
        if (ftpClient == null)
            throw new IOException("ftp server not login");
            isSucc = ftpClient.retrieveFile(remoteFileName, outputStream);
        return isSucc;
    }
    
    /**
     * 上传文件（对象）
     *
     * @param remoteFileName 远程文件名
     * @param file  本地文件对象
     * @return true/false
     * @throws IOException 异常
     */
    public boolean uploadFile(String remoteFileName, File file) throws IOException {
        boolean isSucc;
        try (InputStream inputStream = new FileInputStream(file)) {
            if (ftpClient == null)
                throw new IOException("ftp server not login");
            isSucc = ftpClient.storeFile(remoteFileName, inputStream);
        }
        return isSucc;
    }
    
    /**
     * 上传文件（数据流）
     *
     * @param remoteFileName 远程文件名
     * @param inputStream  二进制流
     * @return true/false
     * @throws IOException 异常
     */
    public boolean uploadFile(String remoteFileName, InputStream inputStream) throws IOException {
        boolean isSucc;
        if (ftpClient == null)
            throw new IOException("ftp server not login");
        isSucc = ftpClient.storeFile(remoteFileName, inputStream);
        return isSucc;
    }
    
    
    /**
     * 删除文件
     * @param remote
     * @return
     * @throws IOException
     */
    public boolean delete(String remote) throws IOException{  
    	try {
        	FTPFile[] files = ftpClient.listFiles(remote);
        	logger.info("files.length=" + files.length);
        	if(files.length >= 1) {
        		return ftpClient.deleteFile(remote);
        	}
		} catch (Exception e) {
			logger.error("ftp删除异常", e);
			e.printStackTrace();
		}
        return false;
    }  
    
    /**
     * 切换目录
     *
     * @param path 创建目录
     * @return 创建标志
     * @throws IOException 异常
     */
    public boolean changeDirectory(String path) throws IOException {
    	boolean flag = ftpClient.changeWorkingDirectory(path);
        logger.info("cd " + path + "结果" + flag);
    	return flag;
    }

    /**
     * 创建目录
     *
     * @param path 创建目录
     * @return 创建标志
     * @throws IOException 异常
     */
    public boolean createDirectory(String path) throws IOException {
        return ftpClient.makeDirectory(path);
    }


    /**
     * 自动关闭资源
     */
    @Override
    public void close() throws Exception {
        if (ftpClient != null && ftpClient.isConnected()) {
            ftpClient.logout();
            ftpClient.disconnect();
        }
    }
    
    // 测试
    public static void main(String[] args) {
    	 try (FtpUtil ftpUtil = new FtpUtil("118.25.102.219",21,"ftpuser","199464")){
    		 File file = new File("C:\\Users\\zhan655\\123.txt");
    		 ftpUtil.uploadFile("4.txt", file);
         }catch (Exception e){
             e.printStackTrace();
         }
	}
}  